<template>
  <div class="pager-container" v-if="pageNumber > 1">
    <a @click="handleClick(1)" :class="{ disabled: current === 1 }">|&lt;&lt;</a>
    <!-- 这里class用对象绑定的方式, 若是需要绑定多个属性可直接在对象中书写, 值为true则表示有该属性 -->

    <!-- 这样绑定事件默认会传递事件参数 -->
    <!-- <a @click="handleClick" :class="{ disabled: current === 1 }">|&lt;&lt;</a> -->
    <!-- 也可以这样写, 这种写法还可以传其他参数
    <a @click="handleClick($event)" :class="{ disabled: current === 1 }">|&lt;&lt;</a>
     -->

    <a @click="handleClick(current - 1)" :class="{ disabled: current === 1 }">&lt;&lt;</a>
    <a
      @click="handleClick(n)"
      v-for="(n, i) in numbers"
      :key="i"
      :class="{ active: n === current }"
    >
      {{ n }}
    </a>
    <a @click="handleClick(current + 1)" :class="{ disabled: current === pageNumber }">&gt;&gt;</a>
    <a @click="handleClick(pageNumber)" :class="{ disabled: current === pageNumber }">&gt;&gt;|</a>
  </div>
</template>

<script>
export default {
  props: {
    current: {
      // 当前页码
      type: Number,
      default: 1,
    },
    total: {
      // 总数据量
      type: Number,
      default: 0,
    },
    limit: {
      // 每页的数据量
      type: Number,
      default: 10,
    },
    visibleNumber: {
      // 能显示的页码
      type: Number,
      default: 10,
    },
  },
  computed: {
    // 计算总页数
    pageNumber() {
      return Math.ceil(this.total / this.limit);
    },
    // 显示页码的数组
    numbers() {
      let min = this.current - Math.floor(this.visibleNumber / 2); // 显示页码的左边界
      min = min < 1 ? 1 : min;
      let max = min + this.visibleNumber - 1; // 显示页码的右边界
      if (max > this.pageNumber) {
        max = this.pageNumber;
        min = max - this.visibleNumber + 1;
        min = min < 1 ? 1 : min;
      }
      const arr = new Array(max - min + 1).fill(min).map((item, i) => item + i);
      // console.log(arr);
      return arr;
    },
  },
  methods: {
    handleClick(newPage) {
      // 抛出一个事件, 事件名为pageChange
      newPage = newPage < 1 ? 1 : newPage;
      newPage = newPage > this.pageNumber ? this.pageNumber : newPage;
      if (newPage === this.current) {
        return;
      }
      this.$emit("pageChange", newPage);
    }
  }
};
</script>

<style lang="less" scoped>
@import "~@/styles/var.less";
// ~@ 表示src文件夹, 而在js脚本里面是用 @
.pager-container {
  display: flex;
  justify-content: center;
  a {
    color: @primary;
    margin: 0 6px;
    cursor: pointer;
    &.disabled {
      color: @lightWords;
      cursor: not-allowed;
    }
    &.active {
      color: @words;
      font-weight: bold;
      cursor: text;
    }
  }
}
</style>
